const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
const fs = require('fs/promises');
const userListFilePath = path.join(__dirname, './data/userList.json');
const studentFilePath = path.join(__dirname, './data/students.json');
const classListFilePath = path.join(__dirname, './data/classList.json');
const workListFilePath = path.join(__dirname, './data/workList.json');

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 3600
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Error handling middleware for JSON parsing
app.use((err, req, res, next) => {
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    return res.status(400).send({ error: 'Invalid JSON body' });
  }
  next();
});
app.post('/api/userList/register', async (req, res) => {
  try {
    // 检查请求体是否包含必要的学生信息
    const { username, password } = req.body;
    if (!username || !password) {
      return res.status(400).send('缺少必要信息');
    }
    
    let userList = [];
    try {
      const data = await fs.readFile(userListFilePath, 'utf8');
      userList = JSON.parse(data);
    } catch (readErr) {
      console.error('读取数据失败:', readErr);
    }
    
    // 创建新学生对象
    const newStudent = {
      id: Date.now().toString(), // 使用时间戳生成唯一ID
      password,
      username,
      createdAt: new Date().toISOString()
    };
    
    // 添加到学生列表
    userList.push(newStudent);
    
    // 写回文件
    await fs.writeFile(userListFilePath, JSON.stringify(userList, null, 2));
    
    res.status(200).json({
      message: '注册成功请登录',
      success: true,
      token: newStudent.id,
      data: newStudent
    });
    // 必须发送响应
    res.status(200).json({
      code: 200,
      success: true,
      message: '成功接收数据',
      token: newStudent.id,
      data: newStudent
    });
  } catch (err) {
    console.error('服务器错误:', err);
    res.status(500).json({ 
      error: '添加学生失败',
      details: err.message 
    });
  }
});
app.post('/api/userList/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // Validate input
    if (!username?.trim() || !password?.trim()) {
      return res.status(400).json({ 
        success: false, 
        message: '用户名和密码不能为空' 
      });
    }

    // Read user data
    const data = await fs.readFile(userListFilePath, 'utf-8');
    const userList = JSON.parse(data);
    
    // Find user
    const user = userList.find(user => user.username === username.trim());
    
    if (!user) {
      return res.status(401).json({ 
        success: false, 
        message: '用户名或密码错误' // Don't reveal if user exists
      });
    }


    if (user.password !== password) {
      return res.status(200).json({ 
        success: false, 
        message: '用户名或密码错误' 
      });
    }

    const token = user.id;
    return res.status(200).json({
      success: true,
      message: '登录成功',
      token,
      user
    });

  } catch (error) {
    console.error('Login error:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，请稍后再试'
    });
  }
});
app.post('/api/student/login', async (req, res) => {
  try {
    const { account, password } = req.body;

    // Validate input
    if (!account?.trim() || !password?.trim()) {
      return res.status(400).json({ 
        success: false, 
        message: '用户名和密码不能为空' 
      });
    }

    // Read user data
    const data = await fs.readFile(studentFilePath, 'utf-8');
    const userList = JSON.parse(data);
    
    // Find user
    const user = userList.find(user => user.account === account.trim());
    
    if (!user) {
      return res.status(401).json({ 
        success: false, 
        message: '用户名错误' // Don't reveal if user exists
      });
    }


    if (user.password !== password) {
      return res.status(200).json({ 
        success: false, 
        message: '密码错误' 
      });
    }

    const token = user.id;
    return res.status(200).json({
      success: true,
      message: '登录成功',
      token,
      user
    });

  } catch (error) {
    console.error('Login error:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，请稍后再试'
    });
  }
});
app.post('/api/student/add', async (req, res) => {
  try {
    // 检查请求体是否包含必要的学生信息
    const { name, age, account, password, gender, classs, number, professional, creditBtn, phone, register, remark } = req.body;
    if (!name || !age || !gender) {
      return res.status(400).send('缺少必要的学生信息');
    }
    
    // 读取现有学生数据
    let students = []; 
    try {
      const data = await fs.readFile(studentFilePath, 'utf8');
      students = JSON.parse(data);
    } catch (readErr) {
      console.error('读取学生数据失败:', readErr);
      // 如果文件不存在或读取失败，创建一个空数组
    }
    
    // 创建新学生对象
    const newStudent = {
      id: Date.now().toString(), // 使用时间戳生成唯一ID
      name,
      account,
      password,
      age,
      gender,
      classs,
      number,
      professional,
      creditBtn,
      phone,
      register,
      remark,
      createdAt: new Date().toISOString()
    };
    
    // 添加到学生列表
    students.push(newStudent);
    
    // 写回文件
    await fs.writeFile(studentFilePath, JSON.stringify(students, null, 2));
    
    res.status(201).json({ message: '学生添加成功', student: newStudent });
    // 必须发送响应
    res.status(200).json({
      code: 200,
      message: '成功接收数据',
      receivedData: req.body
    });
  } catch (err) {
    console.error('服务器错误:', err);
    res.status(500).json({ 
      error: '添加学生失败',
      details: err.message 
    });
  }
});
app.post('/api/student/del', async (req, res) => {
  try {
    console.log('Request body:', req.body);
    
    if (!req.body || !req.body.id) {
      return res.status(400).json({ error: 'Missing student ID' });
    }
    
    const data = await fs.readFile(studentFilePath, 'utf8');
    let students = JSON.parse(data);
    
    // Find the index of the student with the given ID
    const studentIndex = students.findIndex(student => student.id === req.body.id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ error: 'Student not found' });
    }
    
    // Remove the student from the array
    students.splice(studentIndex, 1);
    
    // Write the updated array back to the file
    await fs.writeFile(studentFilePath, JSON.stringify(students, null, 2));
    
    res.json({ success: true, message: `Student with ID ${req.body.id} deleted` });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
app.post('/api/student/edit', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    
    // 验证必要参数
    if (!id) {
      return res.status(400).json({ success: false, message: '学生ID不能为空' });
    }

    // 读取学生数据文件
    const data = await fs.readFile(studentFilePath, 'utf-8');
    let students = JSON.parse(data);

    // 查找要编辑的学生
    const studentIndex = students.findIndex(student => student.id === id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ success: false, message: '未找到该学生' });
    }

    // 更新学生数据（保留未修改的字段）
    students[studentIndex] = {
      ...students[studentIndex],
      ...updateData,
      updatedAt: new Date().toISOString() // 添加更新时间
    };

    // 写回文件
    await fs.writeFile(studentFilePath, JSON.stringify(students, null, 2));

    res.json({
      success: true,
      message: '学生信息更新成功',
      data: students[studentIndex]
    });

  } catch (error) {
    console.error('编辑学生失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，编辑学生失败'
    });
  }
});
app.post('/api/student/submit', async (req, res) => {
  try {
    const { id, imageBase64 } = req.body;
    console.log('req.body', req.body)
    console.log('id', id)
    console.log('imageBase64', imageBase64)
    // 验证必要参数
    if (!id || !imageBase64) {
      return res.status(200).json({ success: false, message: '缺少必要字段' });
    }

    // 读取学生数据文件
    const data = await fs.readFile(studentFilePath, 'utf-8');
    let students = JSON.parse(data);

    // 查找要编辑的学生
    const studentIndex = students.findIndex(student => student.id === id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ success: false, message: '未找到该学生' });
    }

    // 更新学生数据（保留未修改的字段）
    students[studentIndex].imageBase64 = imageBase64
    students[studentIndex].updatedAt = new Date().toISOString() // 添加更新时间

    // 写回文件
    await fs.writeFile(studentFilePath, JSON.stringify(students, null, 2));

    res.json({
      success: true,
      message: '学生作业提交成功',
      data: students[studentIndex]
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器错误，编辑学生失败'
    });
  }
});
app.post('/api/student/list', async (req, res) => {
  try {
    const data = await fs.readFile(studentFilePath, 'utf8');
    const students = JSON.parse(data);
    // 返回结构化响应
    res.status(200).json({
      code: 200,
      success: true,
      data: students,
      message: '学生列表读取成功'
    });
  } catch (err) {
    console.error(err);
    res.status(500).send('读取学生列表失败');
  }
});
app.post('/api/classList/add', async (req, res) => {
  try {
    // 检查请求体是否包含必要的学生信息
    const { name, teacher, number, duration, studenting, studented, introduce } = req.body;
    if (!name) {
      return res.status(400).send('缺少必要信息');
    }
    
    let classList = [];
    try {
      const data = await fs.readFile(classListFilePath, 'utf8');
      console.log('data', data)
      classList = JSON.parse(data);
    } catch (readErr) {
      console.error('读取数据失败:', readErr);
    }
    
    // 创建新学生对象
    const newStudent = {
      id: Date.now().toString(), // 使用时间戳生成唯一ID
      name,
      teacher,
      number,
      duration,
      studenting,
      studented,
      introduce,
      createdAt: new Date().toISOString()
    };
    
    // 添加到学生列表
    classList.push(newStudent);
    console.log('classList', classList)
    // 写回文件
    await fs.writeFile(classListFilePath, JSON.stringify(classList, null, 2));
    
    res.status(201).json({
      message: '课程添加成功',
      class: newStudent
    });
  } catch (err) {
    console.error('服务器错误:', err);
    res.status(500).json({ 
      error: '添加学生失败',
      details: err.message 
    });
  }
});
app.post('/api/classList/del', async (req, res) => {
  try {
    console.log('Request body:', req.body);
    
    if (!req.body || !req.body.id) {
      return res.status(400).json({ error: 'Missing classList ID' });
    }
    
    const data = await fs.readFile(classListFilePath, 'utf8');
    let classList = JSON.parse(data);
    
    // Find the index of the classList with the given ID
    const studentIndex = classList.findIndex(classList => classList.id === req.body.id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ error: 'classList not found' });
    }
    
    // Remove the classList from the array
    classList.splice(studentIndex, 1);
    
    // Write the updated array back to the file
    await fs.writeFile(classListFilePath, JSON.stringify(classList, null, 2));
    
    res.json({ success: true, message: `classList with ID ${req.body.id} deleted` });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
app.post('/api/classList/edit', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    
    // 验证必要参数
    if (!id) {
      return res.status(400).json({ success: false, message: '学生ID不能为空' });
    }

    // 读取学生数据文件
    const data = await fs.readFile(classListFilePath, 'utf-8');
    let classList = JSON.parse(data);

    // 查找要编辑的学生
    const studentIndex = classList.findIndex(classList => classList.id === id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ success: false, message: '未找到该学生' });
    }

    // 更新学生数据（保留未修改的字段）
    classList[studentIndex] = {
      ...classList[studentIndex],
      ...updateData,
      updatedAt: new Date().toISOString() // 添加更新时间
    };

    // 写回文件
    await fs.writeFile(classListFilePath, JSON.stringify(classList, null, 2));

    res.json({
      success: true,
      message: '学生信息更新成功',
      data: classList[studentIndex]
    });

  } catch (error) {
    console.error('编辑学生失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，编辑学生失败'
    });
  }
});
app.post('/api/classList/list', async (req, res) => {
  try {
    const data = await fs.readFile(classListFilePath, 'utf8');
    const classList = JSON.parse(data);
    // 返回结构化响应
    res.status(200).json({
      code: 200,
      success: true,
      data: classList,
      message: '课程列表读取成功'
    });
  } catch (err) {
    console.error(err);
    res.status(500).send('读取学生列表失败');
  }
});
app.post('/api/workList/add', async (req, res) => {
  try {
    // 检查请求体是否包含必要的学生信息
    const { name, status, downDate, upDate, number, creditBtn, remark } = req.body;
    if (!name) {
      return res.status(400).send('缺少必要信息');
    }
    
    let workList = [];
    try {
      const data = await fs.readFile(workListFilePath, 'utf8');
      workList = JSON.parse(data);
    } catch (readErr) {
      console.error('读取数据失败:', readErr);
    }
    
    // 创建新学生对象
    const newStudent = {
      id: Date.now().toString(), // 使用时间戳生成唯一ID
      name,
      status,
      downDate,
      upDate,
      number,
      upDate,
      creditBtn,
      remark,
      createdAt: new Date().toISOString()
    };
    
    // 添加到学生列表
    workList.push(newStudent);
    
    // 写回文件
    await fs.writeFile(workListFilePath, JSON.stringify(workList, null, 2));
    
    res.status(201).json({ message: '作业添加成功', workList: newStudent });
    // 必须发送响应
    res.status(200).json({
      code: 200,
      message: '成功接收数据',
      receivedData: req.body
    });
  } catch (err) {
    console.error('服务器错误:', err);
    res.status(500).json({ 
      error: '添加作业失败',
      details: err.message 
    });
  }
});
app.post('/api/workList/del', async (req, res) => {
  try {
    console.log('Request body:', req.body);
    
    if (!req.body || !req.body.id) {
      return res.status(400).json({ error: 'Missing workList ID' });
    }
    
    const data = await fs.readFile(workListFilePath, 'utf8');
    let workList = JSON.parse(data);
    
    // Find the index of the workList with the given ID
    const studentIndex = workList.findIndex(workList => workList.id === req.body.id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ error: 'workList not found' });
    }
    
    // Remove the workList from the array
    workList.splice(studentIndex, 1);
    
    // Write the updated array back to the file
    await fs.writeFile(workListFilePath, JSON.stringify(workList, null, 2));
    
    res.json({ success: true, message: `workList with ID ${req.body.id} deleted` });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
app.post('/api/workList/edit', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    
    // 验证必要参数
    if (!id) {
      return res.status(400).json({ success: false, message: '学生ID不能为空' });
    }

    // 读取学生数据文件
    const data = await fs.readFile(workListFilePath, 'utf-8');
    let workList = JSON.parse(data);

    // 查找要编辑的学生
    const studentIndex = workList.findIndex(workList => workList.id === id);
    
    if (studentIndex === -1) {
      return res.status(404).json({ success: false, message: '未找到该学生' });
    }

    // 更新学生数据（保留未修改的字段）
    workList[studentIndex] = {
      ...workList[studentIndex],
      ...updateData,
      updatedAt: new Date().toISOString() // 添加更新时间
    };

    // 写回文件
    await fs.writeFile(workListFilePath, JSON.stringify(workList, null, 2));

    res.json({
      success: true,
      message: '学生信息更新成功',
      data: workList[studentIndex]
    });

  } catch (error) {
    console.error('编辑学生失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，编辑学生失败'
    });
  }
});
app.post('/api/workList/list', async (req, res) => {
  try {
    const data = await fs.readFile(workListFilePath, 'utf8');
    const workList = JSON.parse(data);
    // 返回结构化响应
    res.status(200).json({
      code: 200,
      success: true,
      data: workList,
      message: '作业列表读取成功'
    });
  } catch (err) {
    console.error(err);
    res.status(500).send('读取学生列表失败');
  }
});
app.listen(80, () => {
  console.log('服务器运行于 http://127.0.0.1');
});